package com.tg.app.activity.device.settings;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Consumer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tange.base.toolkit.FileUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.backend.service.http.CoreHttpClient;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.device.facade.Status;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.adapter.AlarmAdapter;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.CameraHelper;
import com.tg.app.helper.AlertSoundHelper;
import com.tg.app.helper.AppHelper;
import com.tg.app.util.LogUtils;
import com.tg.app.widget.ACRecyclerView;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.MediaPlayerHelper;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.util.GoogleUtils;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.helper.SoundHelper;
import com.tg.data.http.entity.AlarmToneCapBean;
import com.tg.data.http.entity.DeviceBellBean;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AlertSoundListActivity extends DeviceSettingsBaseActivity{
    public static final String DEFAULT_ID = "9999";
    private static final String TAG = "AlertSoundListActivity";
    private DeviceSettingsInfo info;
    private DeviceFacade deviceFacade;
    private AlarmAdapter alarmAdapter;
    private final MediaPlayerHelper mediaPlayerHelper = new MediaPlayerHelper();
    private String idAlarmTone;
    private String lastIdAlarmTone;
    private String mFrom;
    private AlarmToneCapBean alarmToneCapBean;
    public static final String EXT_CURRENT_LIST_ID = "ext_current_list_id";
    public static final String EXT_SOUND_LIST_FROM = "ext_sound_list_from";
    public static final String EXT_SOUND_LIST_FROM_LAMP = "ext_sound_list_from_lamp";
    public static final String EXT_DEVICE_ALAEM_TONE_CAP = "ext_alarm_tone_cap_bean";
    private List<DeviceBellBean> mList = new ArrayList<>();
    private SoundHelper soundHelper;

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected boolean onBackClick() {
        Intent intent = new Intent();
        intent.putExtra(AlertSoundListActivity.EXT_CURRENT_LIST_ID, idAlarmTone);
        setResult(RESULT_OK, intent);
        return true;
    }

    @Override
    protected void onSetupFailed() {
        TGLog.trace();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        hideActionBar();
        setContentView(R.layout.activity_alert_sound_list);
        getIntentData();
        initView();
        LogUtils.matTrackCustomKVEvent(getBaseContext(), "event_click", "BELL");
    }

    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);
        }
    }

    private void unregisterICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }

    private void getIntentData() {
        Intent intent = getIntent();
        mFrom = intent.getStringExtra(AlertSoundListActivity.EXT_SOUND_LIST_FROM);
        info = intent.getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        deviceFacade = new DeviceFacade(info.uuid);
        alarmToneCapBean = new AlarmToneCapBean(info.uuid, false);
        registerICameraListener();
        deviceFacade.connect();
        AlarmToneCapBean bean = intent.getParcelableExtra(AlertSoundListActivity.EXT_DEVICE_ALAEM_TONE_CAP);
        if (bean != null && bean.getDataSuccess){
            alarmToneCapBean = bean;
        }else{
            CameraHelper.getAlarmToneCap(deviceFacade);
        }


        soundHelper = AlertSoundHelper.getInstance();
        idAlarmTone = soundHelper.getSelectAlarmTone();
        TGLog.d(TAG,"idAlarmTone = " + idAlarmTone);
    }


    @Override
    protected void initView() {
        ACRecyclerView recyclerView = findViewById(R.id.recyclerView_alert_sound);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        backClickEvent();
        mList = soundHelper.getAllList();

        alarmAdapter = new AlarmAdapter(mList, mFrom);
        alarmAdapter.setCheckID(idAlarmTone);
        recyclerView.setVisibility(View.GONE);
        recyclerView.setAdapter(alarmAdapter);
        if (!StringUtils.equalsIgnoreCase(mTitle, ResourcesUtil.getString(R.string.squirrel_repelling))){
            modifyToolBar(R.string.txt_setting_voice);
        }

        recyclerView.addItemDecoration(AlertSoundListActivity.CommItemDecoration.createVertical(AlertSoundListActivity.this));

        findViewById(R.id.tv_add_alert).setVisibility(showAddButton() || StringUtils.equalsIgnoreCase(mTitle, ResourcesUtil.getString(R.string.txt_setting_voice))? View.VISIBLE : View.GONE);
        setClickListener();
    }

    private boolean showAddButton(){
        if (GoogleUtils.isGoogleChannel()){
            return false;
        }

        String language = LanguageUtils.getLanguage(TGApplicationBase.getApplicationContext());
        if (TextUtils.isEmpty(language)){
            return false;
        }
        return language.startsWith("zh-cn");
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setClickListener() {
        alarmAdapter.setOnAlarmClickListener(new AlarmAdapter.OnAlarmClickListener() {
            @Override
            public void onItemPlayClick(int position) {
                List<DeviceBellBean> list = soundHelper.getAllList();
                if (position >= list.size()) {
                    return;
                }

                DeviceBellBean bellBean = list.get(position);
                onAlertSoundItemPlayClick(bellBean);
            }

            @Override
            public void onItemCheck(int position) {
                if (!TGDevice.getInstance().isNetwork(deviceFacade)) {
                    TGToast.showToast(R.string.txt_network_anomaly);
                    return;
                }

                if (position >= mList.size()) {
                    return;
                }
                onAlertSoundItemCheck(position);
            }

            @Override
            public void onItemDel(final int position) {
                DialogUtil.openDlalog(AlertSoundListActivity.this, getString(R.string.txt_delete_voice),
                        null,
                        getString(R.string.message_delete_selected),
                        getString(R.string.dialog_cancel), v1 -> delItem(position), v12 -> {

                        }, ResourcesUtil.getResources().getColor(R.color.drive_btn_record_selected));
            }
        });
        findViewById(R.id.recyclerView_alert_sound).setVisibility(View.VISIBLE);
        alarmAdapter.notifyDataSetChanged();
        findViewById(R.id.tv_add_alert).setOnClickListener(v -> {
            TGLog.d(TAG,"add");
            if (soundHelper.isCustomExceed()){
                TGToast.showToast(R.string.txt_custom_voice_exceed);
            }else{
                addCustom();
            }

        });
    }

    private void onAlertSoundItemPlayClick(DeviceBellBean bellBean) {
        String url = "";
        int id = Integer.parseInt(bellBean.getId());
        if (id > 0) { //自定义语音
            if (bellBean.getUrls() !=  null && bellBean.getUrls().size() > 0){
                url = bellBean.getUrls().get(0);
            }
        }else if (id < 0 && !ResourcesUtil.getString(R.string.txt_current_voice).equals(bellBean.getName())){
            url = soundHelper.getDirectory() + File.separator + bellBean.getName() + SoundHelper.FORMAT_WAV_SUFFIX;
            File file = new File(url);
            if (!file.exists() || !file.isFile()) {
                url = "";
            }
        }
        if (TextUtils.equals(bellBean.getId(), idAlarmTone)) {
            playByDevice();
        }
        if (!TextUtils.isEmpty(url)) {
            playSound(url);
        }
    }

    private void onAlertSoundItemCheck(int position) {
        DeviceBellBean bellBean = mList.get(position);
        if (StringUtils.equals(idAlarmTone, bellBean.getId())){
            return;
        }

        lastIdAlarmTone = idAlarmTone;
        idAlarmTone = bellBean.getId();
        alarmAdapter.setCheckID(idAlarmTone);
        soundHelper.setSelectAlarmTone(idAlarmTone);

        if (Integer.parseInt(idAlarmTone) < 0){
            sendCustomData();
        }else{
            if (position == 0) {
                setAlarmToneData(bellBean.getId(), 1, null);
                return;
            }
            downloadFile(bellBean.getId(), bellBean.getUrls().get(0));
        }

        if (soundHelper.deleteNoExistFile(lastIdAlarmTone)){
            notifyDataListChanged();
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    private void delItem(final int position){
        if (position >= mList.size()) {
            return;
        }

        if (soundHelper.delete(mList.get(position))){
            mList.remove(position);
            alarmAdapter.notifyDataSetChanged();
        }

    }
    private void addCustom() {
        LogUtils.matTrackCustomKVEvent(getBaseContext(), "event_click", "DIY");
        Intent intent = new Intent(getBaseContext(), CustomAlertSoundActivity.class);
        intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
        intent.putExtra(AlertSoundActivity.EXT_AUDIO_CODECS, this.alarmToneCapBean.audioCodecs);
        intent.putExtra(AlertSoundListActivity.EXT_DEVICE_ALAEM_TONE_CAP, this.alarmToneCapBean);

        soundHelper.setAlarmToneCapBean(this.alarmToneCapBean);
        if (StringUtils.equals(AlertSoundListActivity.EXT_SOUND_LIST_FROM_LAMP, mFrom)){
            intent.putExtra(AlertSoundListActivity.EXT_SOUND_LIST_FROM, AlertSoundListActivity.EXT_SOUND_LIST_FROM_LAMP);
        }

        startActivityForResult(intent, 0);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onResume() {
        super.onResume();
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            if (!deviceFacade.connected()) {
                deviceFacade.connect();
            }
        }
        alarmAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterICameraListener();
    }

    private String getCustomDataPath(DeviceBellBean deviceBellBean){
        return soundHelper.getDirectory() + File.separator + deviceBellBean.getName() + SoundHelper.FORMAT_WAV_SUFFIX;

    }
    private void sendCustomData() {
        if (!TGDevice.getInstance().isNetwork(deviceFacade)) {
            resetOldState(R.string.txt_network_anomaly, true);
        } else {
            DeviceBellBean deviceBellBean = soundHelper.getCustomDeviceBellBean();
            if (deviceBellBean != null){
                String path = getCustomDataPath(deviceBellBean);
                File file = new File(path);
                byte[] data = FileUtil.readFile(file);
                if (data != null && data.length > 0) {
                    setAlarmToneData(deviceBellBean.getId(), 0, data);
                }
            }
        }

    }

    private void playByDevice() {
        if (!TGDevice.getInstance().isNetwork(deviceFacade)) {
            TGToast.showToast(R.string.txt_network_anomaly);
        } else {
            if (deviceFacade != null) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_PLAY_ALARMTONE, new byte[4]);
            }
        }
    }


    private void playSound(String play) {
        mediaPlayerHelper.playSound(play);
    }

    private void setAlarmToneData(String id, int type, byte[] content) {
        TGLog.i(TAG, "setAlarmToneData id :%s type:%d", id, type);
        if (!TGDevice.getInstance().isNetwork(deviceFacade)) {
            resetOldState(R.string.txt_network_anomaly, true);
        } else {
            //0:data为音频内容; 1:data为下载音频文件的url
            if (deviceFacade != null) {
                startSendui();
                int ids = Integer.parseInt(id);
                short t = Packet.byteArrayToShort_Little(Packet.intToByteArray_Little(type), 0);
                byte[] data = AVIOCTRLDEFs.Tcis_SetAlarmTone_Req.parseContent(ids, t, this.alarmToneCapBean.fileFormats, this.alarmToneCapBean.audioCodecs, content);
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_SET_ALARMTONE_REQ, data);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            notifyDataListChanged();
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private void notifyDataListChanged() {
        mList = soundHelper.getAllList();
        alarmAdapter.setDeviceBellBeanList(mList);
        alarmAdapter.notifyDataSetChanged();
    }

    private final Consumer<ConnectStatus> connectStatusConsumer = connectStatus -> {
        if (connectStatus.getStatus() == Status.SUCCESS){
            TGLog.d(TAG,"连接成功");
        }else if (connectStatus.getStatus() == Status.FAILED){
            TGLog.d(TAG,"连接失败");
        }
    };

    private final Consumer<Instruction> instructionConsumer = instruction -> {
        if (instruction == null) {
            return;
        }
        final int type = instruction.getId();
        final byte[] data = instruction.getData();
        receiveIOCtrlData(type, data);
    };

    public void receiveIOCtrlData(final int type, final byte[] data) {
        runOnUiThread(() -> {
            if (type == AVIOCTRLDEFs.TCI_CMD_SET_BUZZER_RESP) {
                TGLog.d(TAG,"TCI_CMD_SET_BUZZER_RESP");
                showToast(R.string.setting_success);
                completeSend();
                sendUpdateSettingBroadcast(info);
            } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                int command = Packet.byteArrayToInt_Little(data, 0);
                int result = Packet.byteArrayToInt_Little(data, 4);
                TGLog.i(TAG, "TCI_CMD_SET_COMMAND_RESP");
                TGLog.i(TAG, "command :%d result:%d", command, result);
                completeSend();
                if (command == AVIOCTRLDEFs.TCI_CMD_SET_ALARMTONE_REQ){
                    if (result == 0) {
                        showToast(R.string.setting_success);
                    }else {
                        TGLog.d(TAG,"TCI_CMD_SET_COMMAND_RESP====");
                        resetOldState(R.string.txt_network_anomaly, false);
                    }
                }else if (command == AVIOCTRLDEFs.TCI_CMD_PLAY_AUDIO_REQ) {
                    TGToast.showToast(result == 0 ? R.string.send_success : R.string.txt_network_anomaly);
                }
            }else if (type == AVIOCTRLDEFs.TCI_CMD_GET_ALARMTONE_CAP_RESP) {
                TGLog.d(TAG,"TCI_CMD_GET_ALARMTONE_CAP_RESP");
                alarmToneCapBean.receiveIOCtrlData(data);
            }
        });
    }

    private void downloadFile(final String id, String url) {
        OkHttpClient okHttpClient = CoreHttpClient.getOkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull final IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {

                if (response.isSuccessful()) {
                    try {
                        assert response.body() != null;
                        byte[] data = response.body().bytes();
                        TGLog.i(TAG, "setAlarmToneData downloadFile");
                        setAlarmToneData(id, 0, data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    private void resetOldState(int p, boolean showToast) {
        TGThreadPool.executeOnUiThread(() -> {
            if (showToast) {
                showToast(p);
            }

            TGLog.d(TAG,"TCI_CMD_SET_COMMAND_RESP==== lastIdAlarmTone = " + lastIdAlarmTone + ", idAlarmTone = " + idAlarmTone);
            if (!StringUtils.isEmpty(lastIdAlarmTone)){
                alarmAdapter.setCheckID(lastIdAlarmTone);
                idAlarmTone = lastIdAlarmTone;
            }
        });
    }


    public static class CommItemDecoration extends RecyclerView.ItemDecoration {
        private final int mPaddingLeft;
        private final int mPaddingRight;
        private static final int mSpace = 1;     //间隔
        private final Rect mRect = new Rect(0, 0, 0, 0);
        private final Paint mPaint = new Paint();

        private CommItemDecoration(Context context) {
            mPaint.setColor(context.getResources().getColor(R.color.message_filter_item_bg_normal_color));
            mPaddingLeft = (int) context.getResources().getDimension(R.dimen.message_decrotation_right);
            mPaddingRight = (int) context.getResources().getDimension(R.dimen.message_decrotation_right);
        }

        @Override
        public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.onDraw(c, parent, state);
            drawVertical(c, parent);
        }

        public void drawVertical(@NonNull Canvas c, RecyclerView parent) {
            final int left = parent.getPaddingLeft();
            final int right = parent.getWidth() - parent.getPaddingRight();

            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                        .getLayoutParams();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mSpace;
                mRect.set(left + mPaddingLeft, top, right - mPaddingRight, bottom);
                c.drawRect(mRect, mPaint);
            }
        }


        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0, 0, 0, mSpace);
        }

        public static AlertSoundListActivity.CommItemDecoration createVertical(Context context) {
            return new AlertSoundListActivity.CommItemDecoration(context);
        }
    }
}
